package com.jihad.sbd.modules.sys.oauth2;

import java.security.MessageDigest;
import java.util.UUID;

import com.jihad.sbd.common.exception.MyException;

/**
 * 生成token
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-05-20 14:41
 */
public class TokenGenerator {

    public static String generateValue() {
        return generateValue(UUID.randomUUID().toString());
    }

    private static final char[] hexCode = "0123456789abcdef".toCharArray();
    /**
     * uuid进行md5编码，然后遍历得到的数据每一个字节，根据每个字节的高位和低位去hexCode字符数组中取相应字符
     * 新长度是data的2倍
     * uuid唯一==>data唯一==>最终取到的字符集唯一
     * @param data
     * @return
     */
    public static String toHexString(byte[] data) {
        if(data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length*2);
        for ( byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);//高四位对应的十六进制
            r.append(hexCode[(b & 0xF)]);//低四位对应的十六进制
        }
        return r.toString();
    }

    public static String generateValue(String param) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (Exception e) {
            throw new MyException("生成Token失败", e);
        }
    }
}
